package service;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.User;
import dao.UserDao;
import daoImp.UserDaoImp;

public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		this.doPost(request, response);
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String uname = request.getParameter("uname");
		String upassword = request.getParameter("upassword");
		UserDao dao = new UserDaoImp();
		User user = dao.login(uname, upassword);
		if (user == null) {
			request.setAttribute("meg", "用户名或密码不正确！");
			request.getRequestDispatcher("/Login.jsp").forward(request,
					response);
		}
		else {
			request.getSession().setAttribute("loginUser", user);
			if (user.getIsAdm()) {
				System.out.println(user.getUname() + " sucess");
				request.setAttribute("msg", "管理员：" + uname + ",欢迎访问");
				request.getRequestDispatcher("/Admin_header.jsp").forward(
						request, response);
			} else {
				System.out.println(user.getUname() + " sucess");
				request.setAttribute("msg", "用户：" + uname + ",欢迎访问");
				request.getRequestDispatcher("/User_success.jsp").forward(
						request, response);
			}
		}
		out.flush();
		out.close();
	}

}
